package com.erp.gather.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.gather.domain.*;
import com.ruoyi.gather.api.domain.dto.ComputeFreightDto;
import com.ruoyi.gather.api.domain.vo.ErpCollectProductSkuVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.*;
import com.erp.gather.utils.ChatGptUtils;
import com.esotericsoftware.minlog.Log;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.ae.api.domain.ImageBankParam;
import com.ruoyi.common.core.utils.HttpSendUtils;
import com.ruoyi.common.core.utils.file.ImageUtils;
import com.ruoyi.gather.api.domain.dto.AeAutoProductDto;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.AutoPublishErrorType;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.shop.api.RemoteSellerStoreFreightTemplateService;
import com.ruoyi.shop.api.RemoteSellerStorePriceTemplateService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpowerExtend;
import com.ruoyi.shop.api.domain.ErpSellerStorePriceTemplate;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class AeAutoProductServiceImpl implements IAeAutoProductService {
    private final ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;
    private final ErpCollectProductSkuMapper erpCollectProductSkuMapper;
    private final ErpSellerStoreEuResponsiblePersonMapper erpSellerStoreEuResponsiblePersonMapper;

    static String path = "http://47.94.131.193:8000";

    @Resource
    RemoteSellerStoreFreightTemplateService remoteSellerStoreFreightTemplateService;
    @Resource
    IErpProductPriceControlService iErpProductPriceControlService;
    @Resource
    IAeUploadOssService aeUploadOssService;
    @Resource
    IErpPythonMethodCallService iErpPythonMethodCallService;
    @Resource
    RemoteSellerStorePriceTemplateService remoteSellerStorePriceTemplateService;
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    IAeProductPostErrorService iAeProductPostErrorService;
    @Resource
    IErpUsdExchangeService iErpUsdExchangeService;


    public R<Object> publishAeChoiceProduct(JSONObject productInfoObject) {

        ErpSellerStoreProduct erpSellerStoreProduct = JSONObject.parseObject(productInfoObject.getString("erpSellerStoreProduct"), ErpSellerStoreProduct.class);
        ErpSellerStoreProductExpand erpSellerStoreProductExpand = JSONObject.parseObject(productInfoObject.getString("erpSellerStoreProductExpand"), ErpSellerStoreProductExpand.class);
        List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = JSONArray.parseArray(productInfoObject.getString("erpSellerStoreProductExpand"), ErpSellerStoreProductSku.class);

        ErpSellerProduct erpSellerProduct = JSONObject.parseObject(productInfoObject.getString("erpSellerProduct"), ErpSellerProduct.class);
        ErpSellerProductExpand erpSellerProductExpand = JSONObject.parseObject(productInfoObject.getString("erpSellerProductExpand"), ErpSellerProductExpand.class);
        List<ErpSellerProductSku> erpSellerProductSkuList = JSONArray.parseArray(productInfoObject.getString("erpSellerProductSku"), ErpSellerProductSku.class);

        ErpCollectProduct erpCollectProduct = erpCollectProductMapper.selectById(erpSellerStoreProduct.getCollectProductId());
        ErpCollectProductExpand erpCollectProductExpand = erpCollectProductExpandMapper.selectByCollectProductId(erpSellerStoreProduct.getCollectProductId());
        List<ErpCollectProductSku> erpCollectProductSkuList = erpCollectProductSkuMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getCollectProductId, erpSellerStoreProduct.getCollectProductId())
        );


        JSONObject dto = new JSONObject();
        //渠道seller id （可以在这个API中查询：global.seller.relation.query）， 请使用 business_type = ONE_STOP_SERVICE 的全托管店铺 channel_seller_id
        dto.put("channel_seller_id", "6000122591");
        //渠道（可以在这个API中查询：global.seller.relation.query）
        dto.put("channel", "AE_GLOBAL");
        // 版本号。不传默认是1。 1代表商货融合之前的版本，不能自动创建货品； 2 代表商货融合的版本，需要做货品信息的参数校验，发品成功自动商货绑定。
        dto.put("version", 1);

        //具体商品信息
        JSONObject productDto = new JSONObject();
        dto.put("one_stop_service_product_dto", productDto);

        /** 媒体信息 **/
        JSONObject multimediaDto = new JSONObject();
        //视频信息 暂不上传
        //multimediaDto.put("video_list", null);
        //营销图列表
        JSONArray marketImagesList = new JSONArray();
        JSONObject marketImages = new JSONObject();
        marketImages.put("url", erpSellerStoreProduct.getMarketing());
        marketImages.put("image_type", 1);
        marketImagesList.add(marketImages);
        JSONObject whiteImages = new JSONObject();
        whiteImages.put("url", erpSellerStoreProduct.getWhite());
        whiteImages.put("image_type", 2);
        marketImagesList.add(whiteImages);
        multimediaDto.put("market_image_list", marketImagesList);

        //商品主图列表
        String imageURLs = erpSellerStoreProduct.getImageURLs();
        String imageNewUrl = new String();
        List<String> imageNewList = Arrays.asList(imageURLs.split(";"));
        if (imageNewList.size() > 2) {
            //有两张以上时调序
            //获取第一张
            String imageOne = imageNewList.get(0);
            //获取除第一张的其他List
            List<String> otherElements = imageNewList.subList(1, imageNewList.size());
            Collections.shuffle(otherElements);
            imageNewUrl = imageOne + ";" + StringUtils.join(otherElements, ";");
            System.out.println(imageNewUrl);
        }
        multimediaDto.put("main_image_list", imageNewUrl);
        dto.put("multimedia", multimediaDto);
        /** 媒体信息 **/


        /** 包裹信息 **/
        JSONObject packageDto = new JSONObject();
        //每包的数量
        packageDto.put("lot_num", erpCollectProductExpand.getLotNum());
        //产品的单位
//        packageDto.put("product_unit", null);
        //打包销售: true 非打包销售:false
        packageDto.put("package_type", erpCollectProductExpand.getPackageType());
        dto.put("package_dto", packageDto);
        /** 包裹信息 **/

        /** 扩展信息 **/
        JSONObject productExtDto = new JSONObject();
        //欧盟责任人id，需要调用查询欧盟责任人列表接口：aliexpress.category.eu.responsible.persons.list，获取对应的欧盟责任人列表
        String msrEuId = getEUResponsiblePersonByCategoryId(
                erpCollectProduct.getCategoryId(), erpSellerStoreProduct.getStoreId(), 1);
        if (msrEuId != null) {
            productExtDto.put("msr_eu_id", msrEuId);
        }
        //全托管商品备货类型， 仓发：0 ； 即时补货（JIT）：1 ； 海外备仓：2 。
        productExtDto.put("product_type", 1);
        dto.put("product_ext_dto", productExtDto);
        /** 扩展信息 **/

        /** 商品基本信息 **/
        JSONObject productInfoDto = new JSONObject();
        //商品标题
        JSONObject subject = new JSONObject();
        subject.put("locale", "en_US");
        subject.put("value", erpSellerStoreProduct.getSubject());
        JSONArray subjectList = new JSONArray();
        subjectList.add(subject);
        productInfoDto.put("subject_list", subjectList);

        //商品原发语种：en_US
        productInfoDto.put("locale", "en_US");
        //货币单位。如果不提供该值信息，则默认为"USD"；非俄罗斯卖家这个属性值可以不提供。对于俄罗斯海外卖家，该单位值必须提供，如: "RUB"。
        productInfoDto.put("currency_code", "USD");
        //类目id
        productInfoDto.put("category_id", erpSellerStoreProduct.getCategoryId());
        dto.put("product_info_dto", productInfoDto);
        /** 商品基本信息 **/

        /** 详描列表 **/
        JSONArray detailSourceList = new JSONArray();
        JSONObject detailSource = new JSONObject();
        String makeDetail = makeDetail(erpSellerStoreProduct.getDetail(), erpSellerStoreProduct.getDetailImg());
        detailSource.put("mobile_detail", makeDetail);
        detailSource.put("web_detail", makeDetail);
        detailSource.put("locale", "en_US");
        detailSourceList.add(detailSource);
        dto.put("detail_source_list", detailSourceList);
        /** 详描列表 **/

        /** 商品属性列表 **/
        JSONArray productPropertyList = JSONArray.parseArray(erpSellerStoreProduct.getCustomAttributes());
        dto.put("product_property_list", productPropertyList);
        /** 商品属性列表 **/


        /** 商品sku列表 **/
        JSONArray aeopAeProductSkus = new JSONArray();
        Map<String, ErpCollectProductSku> skuMap = new HashMap<>();
        for (ErpCollectProductSku sku : erpCollectProductSkuList) {
            skuMap.put(sku.getSkuCode(), sku);
        }
        for (ErpSellerStoreProductSku productSku : erpSellerStoreProductSkuList) {
            JSONObject sku = new JSONObject();
            sku.put("sku_code", productSku.getSkuCode());
//            sku.put("sku_discount_price",productSku.getSkuDiscountPrice());
            sku.put("currency_code", "USD");
            // 换算价格
            //如果店铺是USD账户，则进行换算，如果不是则不换算
            BigDecimal skuConversionPrice = BigDecimal.valueOf(0);
//            if (storeExtendSel.getQuotationCurrency().equals("USD")) {
//                skuConversionPrice = BigDecimal.valueOf(Double.valueOf(productSku.getSkuPrice()))
//                        .multiply(BigDecimal.valueOf(100)).divide(newUsdExchange, BigDecimal.ROUND_CEILING);
//                sku.put("sku_price", skuConversionPrice.toString());
//            } else {
            sku.put("supply_price", productSku.getSkuPrice());
//            }
            ErpCollectProductSku collectSku = (ErpCollectProductSku) skuMap.get(productSku.getSkuCode());
            if (ObjectUtils.isNull(collectSku)) {
                continue;
            }

            sku.put("package_weight", collectSku.getSkuWeight().toString());
            sku.put("package_height", collectSku.getSkuHeight().intValue());
            sku.put("package_width", collectSku.getSkuWidth().intValue());
            sku.put("package_length", collectSku.getSkuLength().intValue());
            JSONArray skuPropertyArray = JSONArray.parseArray(productSku.getSkuProperty());
            sku.put("sku_property_value", skuPropertyArray);
            aeopAeProductSkus.add(sku);
        }
        dto.put("product_sku_list", aeopAeProductSkus);
        /** 商品sku列表 **/


        return R.ok();
    }


    @Override
    public R<Object> publishAeProduct(AeAutoProductDto autoProductDto) {

        //生成公共产品库到个人产品库所需要的信息
        R<Object> objectR = autoPrepareWork(autoProductDto);
        if (objectR.getCode() != 200) {
            return R.fail("生成公共产品库到个人产品库所需要的信息异常|" + objectR.getMsg());
        }

        //生成个人商品库到在线商品库所需要的信息
        R<Object> objectR1 = autoPrepareWorkTwo(autoProductDto);
        if (objectR1.getCode() != 200) {
            return R.fail("生成个人商品库到在线商品库所需要的信息异常|" + objectR1.getMsg());
        }

        //整合信息准备上传至速卖通
        R<Object> objectR2 = postProductToAe(autoProductDto);
        if (objectR2.getCode() != 200) {
            return R.fail("整合信息准备上传至速卖通出现异常|" + objectR2.getMsg());
        }

        //调用Ae接口上传至速卖通
        R<Object> objectR3 = remoteAeProductService.autoPublishToAe(autoProductDto);
        System.out.println(objectR3);
        Integer code = (Integer) objectR3.getCode();
        if (!code.toString().equals("200")) {
            // 分析返回请求
            String body = objectR3.getMsg().toString();
            String errorCode = JSONObject.parseObject(body).getJSONObject("error_response")
                    .getString("sub_code");
            String errorMsg = null;
            if (errorCode != null) {
                // 查找错误编码确认对应错误
                AeProductPostError error = iAeProductPostErrorService.selectByErrorCode(errorCode);
                if (error != null) {
                    errorMsg = error.getErrorReason();
                } else {
                    String sub_msg = JSONObject.parseObject(body).getJSONObject("error_response")
                            .getString("sub_msg");
                    errorMsg = sub_msg;
                }
            } else {
                errorMsg = JSONObject.parseObject(body).getJSONObject("error_response").getString("msg");
            }
            autoProductDto.setCode(500);
            autoProductDto.setMsg(errorMsg);
            return R.fail(errorMsg);
        } else {
            String body = objectR3.getData().toString();
            String aeProductId = JSONObject.parseObject(body)
                    .getJSONObject("aliexpress_offer_product_post_response").getJSONObject("result")
                    .getString("product_id");

            autoProductDto.setAeProductId(Long.valueOf(aeProductId));
            autoProductDto.setCode(200);
            return R.ok(autoProductDto);
        }
    }

    @Override
    public R<Object> reissueMessageQueue(AeAutoProductDto autoProductDto) {
        //生成公共产品库到个人产品库所需要的信息
        R<Object> objectR = autoPrepareWork(autoProductDto);

        //生成个人商品库到在线商品库所需要的信息
        R<Object> objectR1 = autoPrepareWorkTwo(autoProductDto);

        //整合信息准备上传至速卖通
        R<Object> objectR2 = postProductToAe(autoProductDto);
        return R.ok(autoProductDto);
    }


    /**
     * 生成公共产品库到个人产品库所需要的信息
     *
     * @param autoProductDto
     * @return
     */
    @Override
    public R<Object> autoPrepareWork(AeAutoProductDto autoProductDto) {
        try {
            ErpCollectProduct collectProduct = autoProductDto.getCollectProduct();
            ErpCollectProductExpand expand = autoProductDto.getCollectProductExpand();
            List<ErpCollectProductSkuVo> productVoSkus = autoProductDto.getCollectProductSkuList();

            //放入类目
            autoProductDto.setCategoryId(collectProduct.getCategoryId());

            //用户id
            Long sellerId = autoProductDto.getSellerId();


            // 刊登以前再次上传图片
            aeUploadOssService.updateProductUrl(collectProduct);

            /** 合并创建新图片 start **/
            String tempWhite = null;
            String tempMarketing = null;
            Integer isOptimize = expand.getIsOptimize();
            String marketing = collectProduct.getMarketing();
            String white = collectProduct.getWhite();
            //确认主图数量，只取六张
            String imageURLs = collectProduct.getImageURLs();
            if (isOptimize == 2 || isOptimize == 0) {
                tempMarketing = marketing;
                tempWhite = white;
            } else {
                //检测商品营销图和白底图问题
                Map<String, Object> marketingMap = ImageUtils.getImgWidthAndHeight(marketing);
                Integer widthNumber = null;
                Integer heightNumber = null;
                if (ObjectUtils.isNotNull(marketingMap)) {
                    //说明有值且获取长宽高 成功
                    widthNumber = (Integer) marketingMap.get("width");
                    heightNumber = (Integer) marketingMap.get("height");
                    if (widthNumber == 750 && heightNumber == 1000) {
                        tempWhite = aeUploadOssService.imageMerge(white, sellerId,
                                collectProduct.getId());
                        tempMarketing = aeUploadOssService.imageMerge(marketing, sellerId,
                                collectProduct.getId());
                    } else {
                        tempWhite = aeUploadOssService.imageMerge(marketing, sellerId,
                                collectProduct.getId());
                        tempMarketing = aeUploadOssService.imageMerge(white, sellerId,
                                collectProduct.getId());
                    }
                } else {
                    return R.fail("产品营销图为空");
                }
            }
            List<String> imgs = Arrays.asList(imageURLs.split(";"));
            String imageNewUrls = String.join(";", imgs.subList(0, Math.min(6, imgs.size())));

            autoProductDto.setImageURLs(aeUploadOssService.imageMerge(imageNewUrls,
                    sellerId, collectProduct.getId()));
            autoProductDto.setWhite(tempWhite);
            autoProductDto.setMarketing(tempMarketing);
            autoProductDto.setDetailImg(aeUploadOssService.imageMerge(collectProduct.getDetailImg(),
                    sellerId, collectProduct.getId()));

            /**
             * 额外保存一份组合完图片的
             */
            autoProductDto.setImageUrlsOld(autoProductDto.getImageURLs());
            autoProductDto.setWhiteOld(tempWhite);
            autoProductDto.setMarketingOld(tempMarketing);
            autoProductDto.setDetailImgOld(autoProductDto.getDetailImg());


            /** 合并创建新图片 end **/

            /** AI生成新标题和详情 start */
            String detailKeyword = expand.getDetailKeyword();
            // 判断关键词个数，关键词太多也不行
            try {
                System.out.println(new Date() + " ************** 1");
                String subject = ChatGptUtils.createTitle(collectProduct.getSubject());

                System.out.println(new Date() + " ************** 2");
                if (subject.length() > 128) {
                    subject = subject.substring(0, 120);
                }

                if (StringUtils.isNotEmpty(subject)) {
                    //调用孙哥接口判断
                    R<Object> objectR = checkViolationWords(subject);

                    System.out.println(new Date() + " ************** 3");
                    if (objectR.getCode() == 200) {
                        //没有侵权词
                        autoProductDto.setSubject(subject);
                    } else {
                        //有侵权词 直接算失败
                        return R.fail("公共库产品有侵权词" + objectR.getData());
//                        String msg = objectR.getMsg();
//
//                        String[] wordsA = subject.split(" ");
//                        String[] wordsB = msg.split(",");
//
//                        StringBuilder result = new StringBuilder();
//                        //侵权词前加 For
//                        for (String word : wordsA) {
//                            boolean contains = false;
//                            for (String b : wordsB) {
//                                if (word.contains(b)) {
//                                    result.append("for ").append(word).append(" ");
//                                    contains = true;
//                                    break;
//                                }
//                            }
//                            if (!contains) {
//                                result.append(word).append(" ");
//                            }
//                            autoProductDto.setSubject(result.toString().trim());
//                        }
                    }
                } else {
                    autoProductDto.setSubject(collectProduct.getSubject());
                }
            } catch (Exception e) {

            }
            try {
                if (StringUtils.isNotEmpty(detailKeyword)) {

                    System.out.println(new Date() + " ************** 4");
                    String detail = ChatGptUtils.createProductDescription(detailKeyword);
                    if (StringUtils.isNotEmpty(detail))
                        autoProductDto.setDetail(detail);
                } else {
                    autoProductDto.setDetail(collectProduct.getDetail());
                }
            } catch (Exception e) {

            }
            /** AI生成新标题和详情 end */

            /** 区域调价 并生成个人商品库sku缓存 start*/
            Map<String, BigDecimal> skuPriceMap = new HashedMap<>();
            String freightMap = expand.getFreightMap();
            List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);

            // 获取运费，修改金额
            for (Dict dict : freightMapList) {
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                    // 添加sku运费价格
                    if (skuPriceMap.containsKey(key)) {
                        BigDecimal price = skuPriceMap.get(key);
                        if (price.compareTo(amount) == 1)
                            skuPriceMap.put(key, amount);
                    } else {
                        skuPriceMap.put(key, amount);
                    }
                }
            }
            List<ErpSellerProductSku> erpSellerProductSkuList = new ArrayList<>();
            for (ErpCollectProductSkuVo erpCollectProductSkuVo : productVoSkus) {
                ErpSellerProductSku erpSellerProductSku = new ErpSellerProductSku();
                BeanUtils.copyProperties(erpCollectProductSkuVo, erpSellerProductSku);
                erpSellerProductSku.setId(null);
                erpSellerProductSku.setCreateTime(null);
                erpSellerProductSku.setUpdateTime(null);
                erpSellerProductSku.setCreateBy(sellerId + "");
                erpSellerProductSku.setUpdateBy(sellerId + "");
                String skuPropertyIds = erpSellerProductSku.getSkuPropertyIds();
                if (skuPriceMap.containsKey(skuPropertyIds)) {
                    BigDecimal minPrice = skuPriceMap.get(skuPropertyIds);

                    // 获取sku
                    BigDecimal skuPrice = new BigDecimal(erpSellerProductSku.getSkuPrice());
                    skuPrice = skuPrice.multiply(new BigDecimal(1.1));

                    // 计算最终价格
                    BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
                            BigDecimal.ROUND_HALF_UP);
                    erpSellerProductSku.setSkuPrice(amount.toString());
                }
                erpSellerProductSkuList.add(erpSellerProductSku);
            }
            autoProductDto.setErpSellerProductSkuList(erpSellerProductSkuList);
            /** 区域调价 并生成个人商品库sku缓存 start*/
            return R.ok(autoProductDto);
        } catch (
                Exception e) {
            return R.fail(e.getMessage());
        }

    }


    /**
     * 生成个人商品库到在线商品库所需要的信息
     */
    public R<Object> autoPrepareWorkTwo(AeAutoProductDto autoProductDto) {
        try {

            ErpCollectProduct collectProduct = autoProductDto.getCollectProduct();
            ErpCollectProductExpand expand = autoProductDto.getCollectProductExpand();
            List<ErpCollectProductSkuVo> productVoSkus = autoProductDto.getCollectProductSkuList();

            // 服务模版设置默认
            autoProductDto.setPromiseTemplateId(0L);
            autoProductDto.setPriceAdjustmentMethod("1");
            autoProductDto.setReadjustPricesType(1);
            //默认自动匹配
            autoProductDto.setIsAutoMate(1);
            //审核中处理方式
            autoProductDto.setIsAudit(1);
            //库存扣减策略
            autoProductDto.setReduceStrategy("payment_success_deduct");
            //默认主图调序
            autoProductDto.setIsMainImageReordering(1);
            //默认加水印
            autoProductDto.setIsAddWatemark(1);
            //库存
            autoProductDto.setStock(199L);

            // 修改商品价格
            Map<String, Object> absoluteQuoteMap = countPrice(
                    autoProductDto.getSellerId(),
                    expand.getAbsoluteQuoteMap(),
                    autoProductDto.getPriceAdjustmentMethod(),
                    autoProductDto.getReadjustPricesType(),
                    null,
                    autoProductDto.getTemplateId(),
                    collectProduct.getProductPrice()
            );
            if (Objects.isNull(absoluteQuoteMap)) {
                autoProductDto.setCode(AutoPublishErrorType.absoluteQuoteError.getCode());
                autoProductDto.setMsg(AutoPublishErrorType.absoluteQuoteError.getInfo());
                return R.fail(autoProductDto);
            }

            //商品一口价价格
            autoProductDto.setProductPrice((String) absoluteQuoteMap.get("productPrice"));

            String customAttributes = collectProduct.getCustomAttributes();
            //0706 速卖通新增 必填属性 高关注化学物质	Hign-concerned Chemical
            String customAttributesTwo = null;
            if (!customAttributes.contains("400000603")) {
                String customAttributesOne = customAttributes.replaceFirst("\\[", "[{\"attr_name_id\":400000603,\"attr_name\":\"Hign-concerned Chemical\",\"attr_value_id\":23399591357,\"attr_value\":null},");
                System.out.println(customAttributesOne);
                //填充品牌至商品属性
                customAttributesTwo = customAttributesOne.replaceFirst("\\[", autoProductDto.getBrandStr());
                System.out.println(customAttributesTwo);
            } else {
                //填充品牌至商品属性
                customAttributesTwo = customAttributes.replaceFirst("\\[", autoProductDto.getBrandStr());
                System.out.println(customAttributesTwo);
            }
            autoProductDto.setCustomAttributes(customAttributesTwo);


            String skuProperty = expand.getSkuProperty();
            List<Dict> skuPropertyList = JsonUtils.parseArrayMap(skuProperty);
            // 创建属性对应map
            Map<String, String> skuPropertyMap = new HashMap<>();
            for (Dict dict : skuPropertyList) {
                List<Map<String, Object>> propertyList = (List<Map<String, Object>>) dict.get("list");
                for (Map<String, Object> propertyMap : propertyList) {
                    skuPropertyMap.put(dict.getStr("value") + ":" + propertyMap.get("value"),
                            propertyMap.get("name") + "");
                }
            }

            // 保存店铺在线商品sku
            List<ErpSellerStoreProductSku> sellerStoreProductSkuList = new ArrayList<>();
            for (ErpSellerProductSku sku : autoProductDto.getErpSellerProductSkuList()) {
                ErpSellerStoreProductSku erpSellerStoreProductSku = new ErpSellerStoreProductSku();
                BeanUtils.copyProperties(sku, erpSellerStoreProductSku);
                erpSellerStoreProductSku.setSkuStock(autoProductDto.getStock());

                BigDecimal skuPrice = new BigDecimal(sku.getSkuPrice());
                BigDecimal readjustPrices = (BigDecimal) absoluteQuoteMap.get("readjustPrices");
                BigDecimal profitNum = (BigDecimal) absoluteQuoteMap.get("profitNum");

                // 计算价格
                if (autoProductDto.getPriceAdjustmentMethod().equals("0")) { // 手动
                    if (readjustPrices != null) {
                        skuPrice = skuPrice.multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                } else { // 智能定价
                    skuPrice = (skuPrice.add(profitNum)).multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                erpSellerStoreProductSku.setSkuPrice(skuPrice.toString());

                String skuPropertyIds = erpSellerStoreProductSku.getSkuPropertyIds();
                String[] split = skuPropertyIds.split(";");

                // 添加属性
                List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
                for (int i = 0; i < split.length; i++) {
                    String string2 = split[i];
                    String[] split2 = string2.split(":");
                    Map<String, Object> map = new HashMap<String, Object>();
                    if (i == 0) {
                        map.put("sku_image", erpSellerStoreProductSku.getSkuImage());
                    }
                    map.put("property_value_definition_name", skuPropertyMap.get(string2));
                    map.put("property_value_id", split2[1]);
                    map.put("sku_property_id", split2[0]);
                    list.add(map);

                }

                erpSellerStoreProductSku.setSkuProperty(JsonUtils.toJsonString(list));
                sellerStoreProductSkuList.add(erpSellerStoreProductSku);
            }
            autoProductDto.setSellerStoreProductSkuList(sellerStoreProductSkuList);

            //保存用户自己调价后的区域定价
            autoProductDto.setAbsoluteQuoteMap((String) absoluteQuoteMap.get("absoluteQuoteMapStr"));
            // 设置系统预制运费模板标识，是否自动匹配运费模板，由前端传过来
            autoProductDto.setSettingFreightTemplateId(expand.getTemplateId());
            System.out.println("运费模版id:" + autoProductDto.getFreightTemplateId());
            //查看运费模板是否有多个发货地 设置海外仓
            if (ObjectUtils.isNotNull(autoProductDto.getFreightTemplateId())) {
                R<Object> freightTemplateLogisticsCompany = remoteSellerStoreFreightTemplateService
                        .getFreightTemplateLogisticsCompany(autoProductDto.getFreightTemplateId(), autoProductDto.getStoreId());
                if (freightTemplateLogisticsCompany.getCode() == 200) {
                    List<String> dataList = (List<String>) freightTemplateLogisticsCompany.getData();
                    if (ObjectUtils.isNotEmpty(dataList)) {
                        autoProductDto.setShipsFromCountry(String.join(",", dataList));
                    }
                }
            }

            return R.ok(autoProductDto);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 发布至速卖通
     */
    public R<Object> postProductToAe(AeAutoProductDto autoProductDto) {

        ErpCollectProduct erpCollectProduct = autoProductDto.getCollectProduct();
        ErpCollectProductExpand erpCollectProductExpand = autoProductDto.getCollectProductExpand();
        List<ErpCollectProductSkuVo> productVoSkus = autoProductDto.getCollectProductSkuList();

        if (productVoSkus.size() == 0) {
            return R.fail("该品在采集表中sku已为空");
        }


        //发布时上传至图片银行
        if (autoProductDto.getPublishType() == 0 || autoProductDto.getPublishType() == 9) {
            // 上传图片至图片银行
            try {
                R<Object> allPicByProductId = sendPicToBank(autoProductDto);
                if (allPicByProductId.getCode() != 200) {
                    return R.fail(allPicByProductId.getMsg());
                }
            } catch (Exception e) {
                return R.fail("图片异常无法上传至图片银行");
            }
        }
        List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = autoProductDto.getSellerStoreProductSkuList();

        //获取店铺延伸表，获取其中的报价币种
        ErpSellerStoreEmpowerExtend storeExtendSel = new ErpSellerStoreEmpowerExtend();
        storeExtendSel.setSellerId(autoProductDto.getStoreId());
        storeExtendSel.setType(1);
        R<Object> storeExtendObject = remoteSellerStoreService.getSellerStoreExtendInfo(storeExtendSel);
        String storeExtendString = JSONObject.toJSONString(storeExtendObject.getData());
        storeExtendSel = JSONObject.parseObject(storeExtendString, ErpSellerStoreEmpowerExtend.class);

        BigDecimal newUsdExchange = iErpUsdExchangeService.getNewUsdExchange();


        //币种 与店铺相关
        autoProductDto.setCurrencyCode(storeExtendSel.getQuotationCurrency());

        /** 从公共采集库获取产品信息 */
        //获取产品自身属性
        JSONArray sellerStoreProductCustomAttributes = JSONArray.parseArray(autoProductDto.getCustomAttributes());
        if (ObjectUtils.isNull(sellerStoreProductCustomAttributes)) {
            return R.fail("Erp产品自身属性为空");
        }
        //获取公共库产品属性
        JSONArray collectProductCustomAttributes = JSONArray.parseArray(erpCollectProduct.getCustomAttributes());
        if (ObjectUtils.isNull(collectProductCustomAttributes)) {
            return R.fail("Erp公共产品库属性为空");
        }

        //品牌
        collectProductCustomAttributes.add(0, sellerStoreProductCustomAttributes.get(0));
        //0706 高关注化学物质
        String s = sellerStoreProductCustomAttributes.toJSONString();
        if (!s.contains("400000603")){
            collectProductCustomAttributes.add(1, sellerStoreProductCustomAttributes.get(1));
        }
        autoProductDto.setCustomAttributesAll(collectProductCustomAttributes.toJSONString());

        Double grossWeight = Double.valueOf(erpCollectProduct.getGrossWeight()) / 1000;
        autoProductDto.setGrossWeight(grossWeight.toString());
        autoProductDto.setPackageHeight(Objects.isNull(erpCollectProduct.getPackageHeight()) ? 10 : erpCollectProduct.getPackageHeight().intValue());
        autoProductDto.setPackageLength(Objects.isNull(erpCollectProduct.getPackageLength()) ? 10 : erpCollectProduct.getPackageLength().intValue());
        autoProductDto.setPackageWidth(Objects.isNull(erpCollectProduct.getPackageWidth()) ? 10 : Integer.valueOf(erpCollectProduct.getPackageWidth()));
        autoProductDto.setProductUnit(erpCollectProduct.getProductUnit());
        autoProductDto.setSizechartId(erpCollectProduct.getSizechartId());

        //批发最小数量
        autoProductDto.setBulkOrder(erpCollectProductExpand.getBulkOrder());
        // 批发折扣
        autoProductDto.setBulkDiscount(erpCollectProductExpand.getBulkDiscount());
        // 每包件数
        autoProductDto.setLotNum(erpCollectProductExpand.getLotNum());
        //购买几件以内不增加运费。取值范围1-1000
        autoProductDto.setBaseUnit(erpCollectProductExpand.getBaseUnit());
        //每增加件数
        autoProductDto.setAddUnit(erpCollectProductExpand.getAddUnit());
        //对应增加的重量
        autoProductDto.setAddWeight(erpCollectProductExpand.getAddWeight());
        //备货期
        autoProductDto.setDeliveryTime(erpCollectProductExpand.getDeliveryTime());
        //打包銷售
        autoProductDto.setPackageType(erpCollectProductExpand.getPackageType());
        //是否自定义计重
        autoProductDto.setIsPackSell(erpCollectProductExpand.getIsPackSell());

        //是否是2.0的品
        String classifyLabel = erpCollectProductExpand.getClassifyLabel();
        if (ObjectUtils.isNotNull(classifyLabel) && classifyLabel.contains("1719179918137212929")) {
            autoProductDto.setProductType(0);
        } else {
            autoProductDto.setProductType(1);
        }

        // 商品详描
        /** 速卖通详描 start**/
        JSONArray detailSourceList = new JSONArray();
        JSONObject detailSource = new JSONObject();
        String makeDetail = makeDetail(autoProductDto.getDetail(), autoProductDto.getDetailImg());
        detailSource.put("mobile_detail", makeDetail);
        detailSource.put("web_detail", makeDetail);
        detailSource.put("locale", "en_US");
        detailSourceList.add(detailSource);
        autoProductDto.setDetailSourceList(detailSourceList);
        /** 速卖通详描 end**/

        /** 速卖通标题 start**/
        JSONObject subject = new JSONObject();
        subject.put("locale", "en_US");
        subject.put("value", autoProductDto.getSubject());
        JSONArray subjectList = new JSONArray();
        subjectList.add(subject);
        autoProductDto.setSubjectList(subjectList);
        /** 速卖通标题 end**/

        /** 营销图和白底图 start**/
        JSONArray marketImagesList = new JSONArray();
        // 营销图
        if (ObjectUtils.isNotEmpty(autoProductDto.getMarketing())) {
            JSONObject marketImages = new JSONObject();
            marketImages.put("url", autoProductDto.getMarketing());
            marketImages.put("image_type", 1);
            marketImagesList.add(marketImages);
        }
        // 白底图
        if (ObjectUtils.isNotEmpty(autoProductDto.getWhite())) {
            JSONObject whiteImages = new JSONObject();
            whiteImages.put("url", autoProductDto.getWhite());
            whiteImages.put("image_type", 2);
            marketImagesList.add(whiteImages);
        }
        autoProductDto.setMarketImages(marketImagesList);
        /** 营销图和白底图 end **/


        /** 主图调序 start**/
        String imageURLs = autoProductDto.getImageURLs();
        List<String> imageNewList = Arrays.asList(imageURLs.split(";"));
        if (imageNewList.size() > 2) {
            //有两张以上时调序
            //获取第一张
            String imageOne = imageNewList.get(0);
            //获取除第一张的其他List
            List<String> otherElements = imageNewList.subList(1, imageNewList.size());
            Collections.shuffle(otherElements);
            String imageNewUrl = imageOne + ";" + StringUtils.join(otherElements, ";");
            System.out.println(imageNewUrl);
            autoProductDto.setImageURLs(imageNewUrl);
        }
        /** 主图调序 end**/

        /**区域定价 start*/
        String absoluteQuoteMapStr = autoProductDto.getAbsoluteQuoteMap();
        if (ObjectUtils.isNotEmpty(absoluteQuoteMapStr)) {
            List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);
            // 获取运费，换算金额
            for (Dict dict : absoluteQuoteMapList) {
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                    // 换算价格
                    if (autoProductDto.getCurrencyCode().equals("USD")) {
                        BigDecimal res = amount.multiply(BigDecimal.valueOf(100)).divide(newUsdExchange,
                                BigDecimal.ROUND_CEILING);
                        absoluteQuoteMap.put(key, res.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    } else {
                        absoluteQuoteMap.put(key, amount.doubleValue());
                    }
                    // 只保留两位小数
                }
            }
            // 获取完成的区域定价
            absoluteQuoteMapStr = JSONObject.toJSONString(absoluteQuoteMapList);
            autoProductDto.setAeopNationalQuoteConfiguration(absoluteQuoteMapStr);
        }
        /**区域定价 end*/

        // 欧盟负责人判别
        Integer type = 1;
        String euResponsiblePersonByCategoryId = getEUResponsiblePersonByCategoryId(
                erpCollectProduct.getCategoryId(), autoProductDto.getStoreId(), type);
        if (euResponsiblePersonByCategoryId != null) {
            autoProductDto.setMsrEuId(euResponsiblePersonByCategoryId);
        }

        JSONArray aeopAeProductSkus = new JSONArray();
        Map<String, ErpCollectProductSkuVo> skuMap = new HashMap<>();
        //将采集表skulist，转为map
        for (ErpCollectProductSkuVo skuVo : productVoSkus) {
            skuMap.put(skuVo.getSkuCode(), skuVo);
        }


        for (ErpSellerStoreProductSku productSku : erpSellerStoreProductSkuList) {
            JSONObject sku = new JSONObject();
            sku.put("sku_code", productSku.getSkuCode());
//            sku.put("sku_discount_price",productSku.getSkuDiscountPrice());
            sku.put("currency_code", autoProductDto.getCurrencyCode());
            // 换算价格
            //如果店铺是USD账户，则进行换算，如果不是则不换算
            BigDecimal skuConversionPrice = BigDecimal.valueOf(0);
            if (storeExtendSel.getQuotationCurrency().equals("USD")) {
                skuConversionPrice = BigDecimal.valueOf(Double.valueOf(productSku.getSkuPrice()))
                        .multiply(BigDecimal.valueOf(100)).divide(newUsdExchange, BigDecimal.ROUND_CEILING);
                sku.put("sku_price", skuConversionPrice.toString());
            } else {
                sku.put("sku_price", productSku.getSkuPrice());
            }
            ErpCollectProductSkuVo collectSku = (ErpCollectProductSkuVo) skuMap.get(productSku.getSkuCode());
            if (ObjectUtils.isNull(collectSku)) {
                continue;
            }

            sku.put("gross_weight", collectSku.getSkuWeight().toString());
            sku.put("package_height", collectSku.getSkuHeight().intValue());
            sku.put("package_width", collectSku.getSkuWidth().intValue());
            sku.put("package_length", collectSku.getSkuLength().intValue());
            sku.put("ipm_sku_stock", productSku.getSkuStock());
            if (productSku.getSkuStock() > 0) {
                sku.put("sku_stock", true);
            } else {
                sku.put("sku_stock", false);
            }
            JSONArray skuPropertyArray = JSONArray.parseArray(productSku.getSkuProperty());
            sku.put("aeop_s_k_u_property", skuPropertyArray);
            sku.put("id", productSku.getSkuPropertyIds());
            aeopAeProductSkus.add(sku);
        }
        autoProductDto.setAeopAeProductSKus(aeopAeProductSkus);


        return R.ok(autoProductDto);

    }

    private void processImages(String imageString, int type, List<ImageBankParam> bankParamList, AeAutoProductDto autoProductDto, String skuCode) {
        if (StringUtils.isNotEmpty(imageString)) {
            List<String> imageList = ListUtil.toList(imageString.split(";"));
            imageList.stream()
//                    .filter(s -> !Pattern.matches("^(http|https)://.*$", s)) // 使用正则表达式判断URL
                    .forEach(s -> {
                        ImageBankParam bankParam = new ImageBankParam();
                        bankParam.setProductId(autoProductDto.getCollectProductId());
                        bankParam.setGroupId("0");
                        bankParam.setSellerId(autoProductDto.getStoreId());
                        bankParam.setStoreUserName(autoProductDto.getStoreUserName());
                        bankParam.setIsAddWatemark(autoProductDto.getIsAddWatemark());
                        bankParam.setType(type);
                        bankParam.setImageUrl(s);
                        if (StringUtils.isNotEmpty(skuCode)) {
                            bankParam.setSkuCode(skuCode);
                        }
                        bankParamList.add(bankParam);
                    });
        }
    }

    private R<Object> sendPicToBank(AeAutoProductDto autoProductDto) {
        List<ImageBankParam> bankParamList = new ArrayList<>();
        List<ImageBankParam> skuParamList = new ArrayList<>();
        // 1.查询商品的所有图片
        // 主图
        String imageURLs = autoProductDto.getImageURLs();
        processImages(imageURLs, 0, bankParamList, autoProductDto, null);
        // 白底图
        String white = autoProductDto.getWhite();
        processImages(white, 1, bankParamList, autoProductDto, null);
        // 营销图
        String marketing = autoProductDto.getMarketing();
        processImages(marketing, 2, bankParamList, autoProductDto, null);
        // 详情图
        String detailImg = autoProductDto.getDetailImg();
        processImages(detailImg, 3, bankParamList, autoProductDto, null);
        // sku图集
        List<ErpSellerStoreProductSku> sellerStoreProductSkuList = autoProductDto.getSellerStoreProductSkuList();
        Map<String, ErpSellerStoreProductSku> map = new HashMap<>();
        for (ErpSellerStoreProductSku sku : sellerStoreProductSkuList) {
            processImages(sku.getSkuImage(), 4, skuParamList, autoProductDto, sku.getSkuCode());
            //将sku转为map
            map.put(sku.getSkuCode(), sku);
        }

        // 2. 将图片传给ae,获取返回的新图
        List<ImageBankParam> returnList = new ArrayList<>();
        for (ImageBankParam imageBankParam : bankParamList) {
            R<Object> imageBankParamObject = remoteAeProductService.uploadImageForSDKTest(imageBankParam);
            if (imageBankParamObject.getCode() != 200) {
                continue;
            }
            String imageBankParamString = JSONObject.toJSONString(imageBankParamObject.getData());
            ImageBankParam imageBankParam1 = JSONObject.parseObject(imageBankParamString, ImageBankParam.class);
            returnList.add(imageBankParam1);
        }

        List<ImageBankParam> returnSkuList = new ArrayList<>();
        for (ImageBankParam imageBankParam : skuParamList) {
            R<Object> imageBankParamObject = remoteAeProductService.uploadImageForSDKTest(imageBankParam);
            if (imageBankParamObject.getCode() != 200) {
                continue;
            }
            String imageBankParamString = JSONObject.toJSONString(imageBankParamObject.getData());
            ImageBankParam imageBankParam1 = JSONObject.parseObject(imageBankParamString, ImageBankParam.class);
            returnSkuList.add(imageBankParam1);
        }

        List<String> errorList = new ArrayList<>();
        for (ImageBankParam imageBankParam : returnList) {
            System.out.println(imageBankParam);
            System.out.println(imageBankParam.toString());
            Long id = imageBankParam.getProductId();
            String newDraw = imageBankParam.getNewDraw();
            String imageUrl = imageBankParam.getImageUrl();
            Integer type = imageBankParam.getType(); // type=4,id表示sku表的主键,其余表示商品表主键
            if (newDraw == null) {
                errorList.add(imageUrl);
                continue;
            }
            if (newDraw.equals("continue")) {
                errorList.add(imageUrl);
                continue;
            }
            switch (type) {
                case 0:
                    imageURLs = imageURLs.replace(imageUrl, newDraw);
                    break;
                case 1:
                    white = white.replace(imageUrl, newDraw);
                    break;
                case 2:
                    marketing = marketing.replace(imageUrl, newDraw);
                    break;
                case 3:
                    detailImg = detailImg.replace(imageUrl, newDraw);
                    break;
            }
        }

        for (ImageBankParam imageBankParam : returnSkuList) {
            Long id = imageBankParam.getProductId();
            String newDraw = imageBankParam.getNewDraw();
            String imageUrl = imageBankParam.getImageUrl();
            if (newDraw == null) {
                errorList.add(imageUrl);
                continue;
            }
            if (newDraw.equals("continue")) {
                errorList.add(imageUrl);
                continue;
            }
            ErpSellerStoreProductSku sku = map.get(imageBankParam.getSkuCode());
            // 获取skuproperty
            sku.setSkuProperty(sku.getSkuProperty().replace(sku.getSkuImage(), newDraw));
            sku.setSkuImage(newDraw);
            map.put(sku.getSkuCode(), sku);
        }

        //for循环，将map转回为list
        List<ErpSellerStoreProductSku> skuNewList = map.values().stream()
                .collect(Collectors.toList());

        if (errorList.size() > 0) {
            return R.fail("异常图片" + errorList);
        }

        autoProductDto.setImageURLs(imageURLs);
        autoProductDto.setMarketing(marketing);
        autoProductDto.setDetailImg(detailImg);
        autoProductDto.setWhite(white);

        autoProductDto.setSellerStoreProductSkuList(skuNewList);
        return R.ok("上传成功");
    }


    /**
     * @param absoluteQuoteMapStr   区域定价
     * @param priceAdjustmentMethod 调价方式：0固定上调，1百分比上调
     * @param readjustPricesType    手动定价类型（0减去 1加上）
     * @param readjustPrices        调价
     * @param templateId            智能定价模板id
     * @param productPrice          商品价格
     * @return
     */
    public Map<String, Object> countPrice(
            Long sellerId,
            String absoluteQuoteMapStr, String priceAdjustmentMethod,
            Integer readjustPricesType, BigDecimal readjustPrices, String templateId, String productPrice) {
        Map<String, Object> map = new HashMap<>();
        map.put("absoluteQuoteMapStr", absoluteQuoteMapStr);
        map.put("productPrice", productPrice);

        Double min = null;
        Double max = null;

        // 获取是否有个别国家关税调整策略
        Map<String, ErpProductPriceControl> controlMap = iErpProductPriceControlService.getListByType("1"); // 关税

        // 判断调价方式
        if (priceAdjustmentMethod.equals("0")) { // 手动
            // 判断是否为0
            if (readjustPrices.compareTo(BigDecimal.ZERO) == 0)
                return map;
            // 判断上调还是下调
            if (readjustPricesType.equals(0)) // 下调
                readjustPrices = readjustPrices.negate();
            readjustPrices = BigDecimal.ONE
                    .add(readjustPrices.divide(new BigDecimal(100)).setScale(4, BigDecimal.ROUND_HALF_UP));

            map.put("readjustPrices", readjustPrices);

            List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);
            // 获取运费，修改金额
            for (Dict dict : absoluteQuoteMapList) {
                String shiptoCountry = (String) dict.get("shiptoCountry");
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                    amount = amount.multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);

                    Double res = amount.doubleValue();
                    absoluteQuoteMap.put(key, res);
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }
                // 计算个别国家调价
                absoluteQuoteMap = controlPrice(controlMap, absoluteQuoteMap, shiptoCountry);
            }
            // 获取完成的区域定价
            absoluteQuoteMapStr = JsonUtils.toJsonString(absoluteQuoteMapList);

        } else if (priceAdjustmentMethod.equals("1")) { // 自动

            List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);

            // 获取模板
            R<Object> priceTemplateObject = new R<>();
            if (ObjectUtils.isNull(templateId)) {
                priceTemplateObject = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateBySellerId(sellerId);
                if (priceTemplateObject.getCode() != 200) {
                    Log.error("未获取到该模版");
                    return null;
                }
            } else {
                priceTemplateObject = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(templateId));
                if (priceTemplateObject.getCode() != 200) {
                    Log.error("未获取到该模版");
                    return null;
                }
            }
            String priceTemplateString = JSONObject.toJSONString(priceTemplateObject.getData());
            ErpSellerStorePriceTemplate priceTemplate = JSONObject.parseObject(priceTemplateString, ErpSellerStorePriceTemplate.class);


            //ErpSellerStorePriceTemplate priceTemplate = (ErpSellerStorePriceTemplate) objectR.getData();

            BigDecimal discount = priceTemplate.getDiscount(); // 折扣比例
            BigDecimal union = priceTemplate.getUnion(); // 联盟比例
            BigDecimal transaction = priceTemplate.getTransaction(); // 交易费比例
            BigDecimal profit = priceTemplate.getProfit(); // 预估利润比例
            Integer type = priceTemplate.getType(); // 类型 1标准比例 2最低利润 3固定利润

            BigDecimal oneHundred = new BigDecimal(100);
            BigDecimal proportion = new BigDecimal(100); // 比例
            BigDecimal profitNum = new BigDecimal(100); // 利润值

            if (type.equals(1)) { // 1 标准比例

                profitNum = BigDecimal.ZERO;

                proportion = (BigDecimal.ONE.add(profit.divide(oneHundred)))
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            } else if (type.equals(2)) { // 2 最低利润

                // 根据区域定价来确定最低的金额，然后最低的金额获取最低的利润值，就是最低利润

                BigDecimal minAmount = null;

                for (Dict dict : absoluteQuoteMapList) {
                    Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                    for (String key : absoluteQuoteMap.keySet()) {
                        BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                        if (minAmount == null) {
                            minAmount = amount;
                        } else {
                            if (minAmount.compareTo(amount) == 1) // 最小值大于本值，就重新赋值
                                minAmount = amount;
                        }
                    }
                }

                // 获取到最小的值，计算利润
                profitNum = minAmount.multiply(profit.divide(oneHundred)).setScale(4, BigDecimal.ROUND_HALF_EVEN);

                // 比例只算联盟、交易、折扣
                proportion = BigDecimal.ONE
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            } else if (type.equals(3)) { // 3 固定利润，利润就是传过来的值

                profitNum = profit;

                // 比例只算联盟、交易、折扣
                proportion = BigDecimal.ONE
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            }

            map.put("readjustPrices", proportion);
            map.put("profitNum", profitNum);

            // 获取运费，修改金额
            for (Dict dict : absoluteQuoteMapList) {
                String shiptoCountry = (String) dict.get("shiptoCountry");
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                    amount = (amount.add(profitNum)).multiply(proportion).setScale(2, BigDecimal.ROUND_HALF_UP);

                    Double res = amount.doubleValue();
                    absoluteQuoteMap.put(key, res);
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }
                // 计算个别国家调价
                absoluteQuoteMap = controlPrice(controlMap, absoluteQuoteMap, shiptoCountry);
            }
            // 获取完成的区域定价
            absoluteQuoteMapStr = JsonUtils.toJsonString(absoluteQuoteMapList);
        }

        productPrice = min.equals(max) ? min + "" : min + "-" + max;
        map.put("productPrice", productPrice);
        map.put("absoluteQuoteMapStr", absoluteQuoteMapStr);
        return map;
    }

    /**
     * 计算个别国家调价
     *
     * @param controlMap
     * @param absoluteQuoteMap
     * @param shiptoCountry
     * @return
     */
    private Map<String, Object> controlPrice(Map<String, ErpProductPriceControl> controlMap,
                                             Map<String, Object> absoluteQuoteMap, String shiptoCountry) {

        // 判断该国家是否需要调价
        if (controlMap.containsKey(shiptoCountry)) {

            ErpProductPriceControl control = controlMap.get(shiptoCountry);

            for (String key : absoluteQuoteMap.keySet()) {
                BigDecimal price = new BigDecimal((Double) absoluteQuoteMap.get(key));

                String controlWay = control.getControlWay(); // 调价方式（1固定 2百分比）
                String priceType = control.getPriceType(); // 加减类型 （1加上 2减去）
                BigDecimal amount = new BigDecimal(control.getAmount()); // 价格

                if (controlWay.equals("1")) { // 固定
//					if (priceType.equals("1")) { // 加上
                    price = price.add(amount);
//					} else if (priceType.equals("2")) { // 减去
//						price = price.subtract(amount);
//					}
                } else if (controlWay.equals("2")) { // 百分比
                    BigDecimal subtract = BigDecimal.ONE.subtract(amount.divide(BigDecimal.valueOf(100)));
                    price = price.divide(subtract, 2,
                            BigDecimal.ROUND_HALF_UP);
//					if (priceType.equals("1")) { // 加上
//						price = price.add(amount);
//					} else if (priceType.equals("2")) { // 减去
//						price = price.subtract(amount);
//					}
                }
                Double res = price.doubleValue();
                absoluteQuoteMap.put(key, res);
            }
        }

        return absoluteQuoteMap;
    }

    /**
     * 商品详描处理
     *
     * @param detail
     * @param imgUrls
     * @return
     */
    public String makeDetail(String detail, String imgUrls) {
        Map<String, Object> map = new HashMap<>();
        map.put("version", "2.0.0");
        Map<String, Object> map1 = new LinkedMap<String, Object>();
        map1.put("type", "text-image");

        // 文本
        List<Object> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(detail)) {
            String[] split = detail.split("\n");
            for (String string : split) {
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("content", string);
                map2.put("class", "body");
                list.add(map2);
            }
        }

        // 图片
        List<Object> list2 = new LinkedList<>();
        String[] split2 = imgUrls.split(";");
        for (String string : split2) {
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("url", string);
            map2.put("style", new HashMap<>());
            list2.add(map2);
        }

        if (list != null && list.size() != 0)
            map1.put("texts", list);
        if (list2 != null && list2.size() != 0)
            map1.put("images", list2);
        List<Object> resList = new ArrayList<Object>();
        resList.add(map1);
        map.put("moduleList", resList);
        return JsonUtils.toJsonString(map);
    }

    public String getEUResponsiblePersonByCategoryId(Long categoryId, Long sellerStoreId, Integer type) {
        // sellerStoreId为当前登录账号id

        // 判断该店铺是否存在并已授权
        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(sellerStoreId);
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStoreEmpower erpSellerStoreEmpower = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);
        if (erpSellerStoreEmpower == null || erpSellerStoreEmpower.getIsEmpower().equals("0")) {
            return null;
        }
        // 获取该店铺该类目下的信息是否存在
        if (type == 1) {
            //测试正常
            ErpSellerStoreEuResponsiblePerson erpSellerStoreEuResponsiblePerson = erpSellerStoreEuResponsiblePersonMapper
                    .selectOne(new LambdaQueryWrapper<ErpSellerStoreEuResponsiblePerson>()
                            .eq(ErpSellerStoreEuResponsiblePerson::getCategoryId, categoryId)
                            .eq(ErpSellerStoreEuResponsiblePerson::getSellerStoreId, sellerStoreId)
                            .last("limit 1"));
            if (erpSellerStoreEuResponsiblePerson != null) {
                // 若存在，返回该值
                return erpSellerStoreEuResponsiblePerson.getMsrEuId().toString();
            } else {
                // 若不存在，调用AE接口，该类目下的欧盟负责人

                return getEUResponsiblePersonFromAe(categoryId, sellerStoreId);
            }
        } else {
            return getEUResponsiblePersonFromAe(categoryId, sellerStoreId);
        }
    }

    //调用AE接口获取该类目下的欧盟负责人
    public String getEUResponsiblePersonFromAe(Long categoryId, Long sellerStoreId) {
        R<Object> objectR = remoteAeProductService.getEUResponsiblePersonFromAeInnerAuth(categoryId, sellerStoreId);
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/getEUResponsiblePersonFromAe?categoryId="
//                        + categoryId + "&sellerId=" + sellerStoreId, String.class);
//        String body = (String) forEntity.getBody();
        String body = JSONObject.toJSONString(objectR.getData());
        Dict dict = JsonUtils.parseMap(body);
        if (Integer.valueOf(dict.get("code").toString()) == 500) {
            return null;
        }
        // 存储数据
        ErpSellerStoreEuResponsiblePerson erpSellerStoreEuResponsiblePerson =
                erpSellerStoreEuResponsiblePersonMapper.selectOne(
                        new LambdaQueryWrapper<ErpSellerStoreEuResponsiblePerson>()
                                .eq(ErpSellerStoreEuResponsiblePerson::getSellerStoreId, sellerStoreId)
                                .eq(ErpSellerStoreEuResponsiblePerson::getCategoryId, categoryId)
                );
        if (erpSellerStoreEuResponsiblePerson == null) {
            erpSellerStoreEuResponsiblePerson = new ErpSellerStoreEuResponsiblePerson();
        }
        erpSellerStoreEuResponsiblePerson.setSellerStoreId(sellerStoreId);
        erpSellerStoreEuResponsiblePerson.setCategoryId(categoryId);
        erpSellerStoreEuResponsiblePerson.setSupport(dict.get("support").toString());
        Boolean flag = false;
        if (erpSellerStoreEuResponsiblePerson.getSupport().equals("true")) {
            erpSellerStoreEuResponsiblePerson.setMsrEuId(Long.valueOf(dict.get("msr_eu_id").toString()));
            erpSellerStoreEuResponsiblePerson.setName(dict.get("name").toString());
            flag = true;
        } else {
            erpSellerStoreEuResponsiblePerson.setMsrEuId(Long.valueOf(-2));
            erpSellerStoreEuResponsiblePerson.setName("暂无欧盟负责人");
        }
        if (erpSellerStoreEuResponsiblePersonMapper.insertOrUpdate(erpSellerStoreEuResponsiblePerson)) {
            if (flag) {
                return erpSellerStoreEuResponsiblePerson.getMsrEuId().toString();
            } else {
                return null;
            }
        } else {
            return null;
        }
    }


    /**
     * 检测侵权词
     *
     * @param newSubject
     * @return
     */
    @Override
    public R<Object> checkViolationWords(String newSubject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", newSubject);
        String body = HttpSendUtils.getReturnPostBody(jsonObject.toJSONString(), path + "/checkViolationWords");
        System.out.println(body);
        JSONObject bodyJson = JSONObject.parseObject(body);
        if (ObjectUtils.isNull(bodyJson.getString("data"))) {
            //无侵权词
            return R.ok("无侵权词");
        } else {
            //有侵权词
            String data = bodyJson.getString("data");
            return R.fail(data);
        }
    }

    @Override
    public R<Object> uploadTestProduct(ComputeFreightDto autoProductDto) {
//        AeAutoProductDto dto = new AeAutoProductDto();
//        dto.setStoreUserName(project.getStoreUserName());
//        dto.setTemplateId(project.getTemplateId());
//        dto.setStoreId(task.getStoreId());
//
//
//        dto.setProductBrand(project.getProductBrand());
//        dto.setCollectProductId(task.getCollectProductId());
//        dto.setIsAfflicateDiscount(project.getIsAfflicateDiscount());
//        dto.setAfflicateDiscount(project.getAfflicateDiscount());
//        dto.setMethodType(1);
//        publishAeProduct(aeAutoProductDto);
        return null;
    }


}
